package it.jack.practicertmp;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 遇到四个问题
 * 1.sdk设置为32 提示报错
 * 2.直播有时候需要重新关闭后再开启
 * 3.手机需要晃动一下，直播才显示出来
 * 4.sendVideo中的关键帧和非关键帧需要连续性的发送
 */
public class MainActivity extends AppCompatActivity {
    //B站现在无法推流，具体原因不明
    //private String url = "rtmp://bdy.live-push.bilivideo.com/live-bvc/?streamname=live_472621980_33273626&key=a4492df7d8dc13d115b45ff9fbbab8bd&schedule=rtmp&pflag=1";
    private String                 url = "rtmp://47.106.181.107/live/test";//测试通过
    private MediaProjectionManager mediaProjectionManager;
    private MediaProjection        mediaProjection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        checkPermission();
    }

    public boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO
            }, 1);

        }
        return false;
    }

    public void startLive(View view) {
        this.mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, 100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            ScreenLive screenLive = new ScreenLive();
            screenLive.startLive(url, mediaProjection);
        }
    }

}